package com.bite.Queue;

public class MyBlockingQueue {
    private volatile int head;
    //队尾
    private volatile int rear;
    //有效个数
    private volatile int usedSize;
    //数组实现
    private int[] queue;
    //构造方法
    MyBlockingQueue(int value) {
        queue = new int[value];
    }
    //插入数据
    public boolean enQueue(int value) throws InterruptedException {
        synchronized (this) {
            while (isFull()) {
                wait();
            }
            queue[rear] = value;
            rear = (rear + 1) % queue.length;
            usedSize++;
            notifyAll();
            return true;
        }
    }
    //取出数据
    public int deQueue() throws InterruptedException {
        synchronized (this) {
            while (isEmpty()) {
                wait();
            }
            int value = queue[head];
            head = (head + 1) % queue.length;
            usedSize--;
            notifyAll();
            return value;
        }
    }
    //是否为空
    public boolean isEmpty() {
        return usedSize == 0;
    }
    //是否满了
    public boolean isFull() {
        return usedSize == queue.length;
    }

}
